package com.example.jetpacklearn
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.lifecycle.ViewModelProvider
import com.example.jetpacklearn.liftcycle.ActivityLifeObserver
import com.example.jetpacklearn.liftcycle.RecommendViewModel
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() ,View.OnClickListener {

    private val playerPresenter by lazy {
        PlayerPresenter.instance
    }

    init {
        lifecycle.addObserver(ActivityLifeObserver())
    }

    companion object {
        private const val TAG = "MainActivity"
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        initView()
        initDataListener()

    }

    /**
     * 对数据进行监听
     */
    private fun initDataListener() {

        playerPresenter.liveDataMusic.observe(this) {
            Log.d(TAG, "initDataListener liveDataMusic: ${it?.title}")
        }

        playerPresenter.currentLifeMusic.observe(this) {
            tvMainPlayerMessage.text = it?.title
            Log.d(TAG, "initDataListener currentLifeMusic: ${it?.title}")
        }

        playerPresenter.currentMusic.addListener (this){
            // 音乐内容发生变化 更新UI
//            tvMainPlayerMessage.text = it?.title
            Log.d(TAG, "initDataListener currentMusic: ${it?.cover}")
        }

        playerPresenter.playStatus.addListener (this){
            when (it) {
                PlayerPresenter.PlayStatus.PLAYING -> {
                    btnMainPlayerPlayStatus.text = "点击停止"
                }
                else -> {
                    btnMainPlayerPlayStatus.text = "点击播放"
                }
            }
        }

        val recommendViewModel = ViewModelProvider(this).get(RecommendViewModel::class.java)
        recommendViewModel.musicList.observe(this) {
            Log.d(TAG, "initDataListener: ${it.size}" )
        }

    }

    private fun initView() {
        btnMainPlayerNext.setOnClickListener(this)
        btnMainPlayerPlayStatus.setOnClickListener(this)
        btnMainPlayerPrevious.setOnClickListener(this)
        btnMainNextActivity.setOnClickListener(this)
    }

    override fun onClick(v: View?) {
        when (v) {
            btnMainPlayerNext -> {
                playerPresenter.doPlayNext()
            }
            btnMainPlayerPlayStatus -> {
                playerPresenter.doPlayOrPause()
            }
            btnMainPlayerPrevious -> {
                playerPresenter.doPlayPrevious()
            }
            btnMainNextActivity -> {
                val intent = Intent(this, PlayerActivity::class.java)
                startActivity(intent)
            }
            else -> {
                Log.d(TAG, "onClick: else")
            }
        }
    }

}